package com.github.caijinglong.handler

import com.github.caijinglong.SaveDataHandler
import com.github.caijinglong.SavedDataType
import com.github.caijinglong.bind
import com.github.caijinglong.ext.println
import com.github.caijinglong.save
import org.json.JSONArray
import org.json.JSONObject

class SimpleBattleHandler : SaveDataHandler {
    override var jsonObject: JSONObject = JSONObject()

    fun addSimpleBatterCount(count: Int) {
        jsonObject.getJSONArray("relics").apply {
            if (this.count() <= 1) {
                this.put("NeowsBlessing")
                jsonObject.getJSONArray("relic_counters").apply {
                    put(count)
                }
                return@apply
            }
            if (this.getString(1) != "NeowsBlessing") {
//                this.put(1, "NeowsBlessing")
                this.insert(1, "NeowsBlessing")

                jsonObject.getJSONArray("relic_counters").apply {
                    insert(1, count)
                }
            } else {
                jsonObject.getJSONArray("relic_counters").apply {
                    change(1, count)
                }
            }
        }
    }

    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            SimpleBattleHandler().apply {
                bind(SavedDataType.ZS)
                addSimpleBatterCount(35)
//                jsonObject.println()
//                addSimpleBatterCount(1)
                save(SavedDataType.ZS)
            }
        }
    }
}

fun JSONArray.insert(index: Int, obj: Any) {
    val list = this.toMutableList()
    list.add(index, obj)
    this.removeAll { true }
    list.forEach {
        this.put(it)
    }
}


fun JSONArray.change(index: Int, obj: Any) {
    remove(index)
    insert(index, obj)
}